<template>
  <basic-container>
    <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.role_delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
        <el-button size="small"
                   icon="el-icon-s-tools"
                   @click="handleRole"
                   plain>权限设置
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="角色权限配置"
               class="tab_dialog"
               :visible.sync="box"
               :append-to-body="true"
               width="345px">
      <div style="height: 100%" class="tab_box">
        <el-tabs type="border-card">
          <el-tab-pane label="顶部菜单权限">
            <div>
              <el-tree :data="toMenuList"
                       show-checkbox
                       node-key="id"
                       ref="topMenu"
                       :default-checked-keys="topMenuObj"
                       :props="topMenuProps">
              </el-tree>
            </div>
          </el-tab-pane>
          <el-tab-pane label="菜单权限">
            <div >
              <el-tree :data="menuGrantList"
                       show-checkbox
                       node-key="id"
                       ref="treeMenu"
                       :default-checked-keys="menuTreeObj"
                       :props="props">
              </el-tree>
            </div>
          </el-tab-pane>
          <el-tab-pane label="数据权限" v-if="showMenu">
            <div>
              <el-tree :data="dataScopeGrantList"
                       show-checkbox
                       node-key="id"
                       ref="treeDataScope"
                       :default-checked-keys="dataScopeTreeObj"
                       :props="props">
              </el-tree>
            </div>
          </el-tab-pane>
          <el-tab-pane label="接口权限" v-if="showMenu">
            <div>
              <el-tree :data="apiScopeGrantList"
                       show-checkbox
                       node-key="id"
                       ref="treeApiScope"
                       :default-checked-keys="apiScopeTreeObj"
                       :props="props">
              </el-tree>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="box = false">取 消</el-button>
        <el-button type="primary"
                   @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
    import {add, getList, getRole, getRoleTree, grant, grantTree, remove, update,} from "@/api/system/role";
    import { getTopMenu } from "@/api/system/topmenu"
    import {mapGetters} from "vuex";
    import website from '@/config/website';

    export default {
        data() {
            return {
                showMenu: false,
                form: {},
                box: false,
                props: {
                    label: "title",
                    value: "key"
                },
                topMenuProps:{
                  label: "name",
                  value:'id'
                },
                toMenuList: [],
                menuGrantList: [],
                dataScopeGrantList: [],
                apiScopeGrantList: [],
                apiGrantList: [],
                topMenuObj:[],
                menuTreeObj: [],
                dataScopeTreeObj: [],
                apiScopeTreeObj: [],
                selectionList: [],
                query: {},
                loading: true,
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                option: {
                    tip: false,
                    tree: true,
                    border: true,
                    index: true,
                    selection: true,
                    viewBtn: true,
                    columnBtn:false,
                    dialogWidth: 300,
                    dialogHeight: 400,
                    column: [
                        {
                            label: "角色名称",
                            prop: "roleName",
                            search: true,
                            span: 24,
                            rules: [
                                {
                                    required: true,
                                    message: "请输入角色名称",
                                    trigger: "blur"
                                }
                            ]
                        },
                        {
                            label: "所属企业",
                            prop: "tenantId",
                            type: "tree",
                            dicUrl: "/api/blade-system/tenant/select",
                            addDisplay: false,
                            editDisplay: false,
                            viewDisplay: website.tenantMode,
                            span: 24,
                            props: {
                                label: "tenantName",
                                value: "tenantId"
                            },
                            hide: !website.tenantMode,
                            search: website.tenantMode,
                            rules: [{
                                required: true,
                                message: "请输入所属企业",
                                trigger: "click"
                            }]
                        },
                        {
                            label: "角色别名",
                            prop: "roleAlias",
                            search: true,
                            span: 24,
                            rules: [
                                {
                                    required: true,
                                    message: "请输入角色别名",
                                    trigger: "blur"
                                }
                            ]
                        },
                        {
                            label: "上级角色",
                            prop: "parentId",
                            dicData: [],
                            type: "tree",
                            hide: true,
                            span: 24,
                            props: {
                                label: "title"
                            },
                            rules: [
                                {
                                    required: false,
                                    message: "请选择上级角色",
                                    trigger: "click"
                                }
                            ]
                        },
                        {
                            label: "角色排序",
                            prop: "sort",
                            type: "number",
                            span: 24,
                            rules: [
                                {
                                    required: true,
                                    message: "请输入角色排序",
                                    trigger: "blur"
                                }
                            ]
                        }
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permission.role_add, false),
                    viewBtn: this.vaildData(this.permission.role_view, false),
                    delBtn: this.vaildData(this.permission.role_delete, false),
                    editBtn: this.vaildData(this.permission.role_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);

                });
                return ids.join(",");
            },
            idsArray() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids;
            }
        },
        methods: {
            submit() {
                const menuList = this.$refs.treeMenu.getCheckedKeys();
                const dataScopeList = this.$refs.treeDataScope ? this.$refs.treeDataScope.getCheckedKeys() : [];
                const apiScopeList = this.$refs.treeApiScope ? this.$refs.treeApiScope.getCheckedKeys() : [];
                const toMenuList = this.$refs.topMenu.getCheckedKeys();
                grant(this.idsArray, menuList, dataScopeList, apiScopeList, toMenuList).then(() => {
                    this.box = false;
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    this.onLoad(this.page);
                });
            },
            rowSave(row, loading, done) {
                add(row).then(() => {
                    loading();
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                }, error => {
                    done();
                    console.log(error);
                });
            },
            rowUpdate(row, index, loading, done) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    loading();
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                }, error => {
                    done();
                    console.log(error);
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },

            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params) {
                this.query = params;
                this.onLoad(this.page, params);
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            handleRole() {
                if (this.selectionList.length !== 1) {
                    this.$message.warning("只能选择一条数据");
                    return;
                }
                this.menuTreeObj = [];
                this.dataScopeTreeObj = [];
                this.apiScopeTreeObj = [];
                this.topMenuObj = [];
                grantTree()
                    .then(res => {
                        this.menuGrantList = res.data.data.menu;
                        this.dataScopeGrantList = res.data.data.dataScope;
                        this.apiScopeGrantList = res.data.data.apiScope;
                        getRole(this.ids).then(res => {
                            this.menuTreeObj = res.data.data.menu;
                            this.dataScopeTreeObj = res.data.data.dataScope;
                            this.apiScopeTreeObj = res.data.data.apiScope;
                            this.box = true;
                        });
                    });
                getTopMenu(this.selectionList[0].id).then(res => {
                    this.toMenuList = res.data.data

                    this.toMenuList.forEach(value => {
                        if(value.name == '服务系统管理') {
                            this.showMenu = true
                        }
                    })

                    getRole(this.ids).then(res => {
                        this.topMenuObj = res.data.data.topMenu
                        this.box = true;
                    });
                })
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            onLoad(page, params = {}) {
                this.loading = true;
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    this.data = res.data.data;
                    getRoleTree().then(res => {
                        const data = res.data.data;
                        const index = this.$refs.crud.findColumnIndex("parentId");
                        this.option.column[index].dicData = data;
                    });
                    this.loading = false;
                    this.selectionClear();
                });
            }
        }
    };
</script>

<style lang="scss">
  .tab_dialog{
    .el-dialog{
      height: 100%;
    }
    .el-dialog__body{
      height: calc(100% - 140px);
    }
    .tab_box{
      .el-tabs--border-card{
        height: 100%;
      }
      .el-tabs__content{
        max-height: calc(100% - 72px);
        overflow-y: auto !important;
      }
    }
  }
</style>
